package com.rykj.qxj.test.restTemplateTest;


import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rykj.qxj.result.BaseResponse;
import com.rykj.qxj.util.SignUtil;


public class RestTemplateUtils {
	private static Logger logger = LoggerFactory.getLogger(RestTemplateUtils.class);

	protected RestTemplate restTemplate;
	protected HttpHeaders headers;
	protected HttpEntity<Object> request;
	protected ResponseEntity<Object> response;

	/**
	 * @Description: 登录获取长时令牌
	 * @param appId
	 *            应用id
	 * @param appKey
	 *            应用密码
	 * @param signerId
	 *            用户id 可选参数
	 * @param url
	 *            请求url
	 * @author
	 */
	public static String login(String userName, int age, String address, String url,String appKey) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("appKey", appKey);
		JSONObject t = new JSONObject();
		t.put("name", userName);
		t.put("age", age);
		String sign = SignUtil.createSign(t, appKey);
		t.put("sign", sign);
		HttpEntity<Object> request = new HttpEntity<Object>(t, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
		ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, request,
				String.class);
		System.out.println(exchange.toString());
		Object body = exchange.getBody();
		//System.out.println(body.toString());
		
		return body.toString();
		
	}
	public static BaseResponse doPost(Map<String,Object> paramMap, String url,String appKey) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("appKey", appKey);
		String sign = SignUtil.createSign(paramMap, appKey);
		paramMap.put("sign", sign);
		HttpEntity<Object> request = new HttpEntity<Object>(paramMap, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
	    BaseResponse result = restTemplate.postForObject(url, request, BaseResponse.class);
		return result;
		
		
	}
	public static String doGet(Map<String,Object> paramMap,String url,String appKey) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("appKey", appKey);
		
		String sign = SignUtil.createSign(paramMap, appKey);
		paramMap.put("sign", sign);
		HttpEntity<Object> request = new HttpEntity<Object>(paramMap, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
		ResponseEntity<BaseResponse> exchange = restTemplate.exchange(url, HttpMethod.GET, request,
				BaseResponse.class);
		System.out.println(exchange.toString());
		return exchange.getBody().toString();
	
	}
	public static String doPut(Map<String,Object> paramMap,String url,String appKey) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("appKey", appKey);
		String sign = SignUtil.createSign(paramMap, appKey);
		paramMap.put("sign", sign);
		HttpEntity<Object> request = new HttpEntity<Object>(paramMap, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
		ResponseEntity<BaseResponse> exchange = restTemplate.exchange(url, HttpMethod.PUT, request,
				BaseResponse.class);
		System.out.println(exchange.toString());
		Object body = exchange.getBody();
		return body.toString();
		
	}
	public static String doDelete(Map<String,Object> paramMap,String url,String appKey) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		headers.set("appKey", appKey);
		
		String sign = SignUtil.createSign(paramMap, appKey);
		paramMap.put("sign", sign);
		HttpEntity<Object> request = new HttpEntity<Object>(paramMap, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
		ResponseEntity<BaseResponse> exchange = restTemplate.exchange(url, HttpMethod.DELETE, request,
				BaseResponse.class);
		System.out.println(exchange.toString());
		Object body = exchange.getBody();
		return body.toString();
		
	}
	public static void main(String[] args) {
		/*logger.info("===========post request start======================");
		String postUrl="http://localhost:8080/postrequest";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", "张01001703");
		paramMap.put("age", 23);
		for(int i=0;i<50;i++) {
			BaseResponse doPost = doPost(paramMap,postUrl,"000000");
			System.out.println(doPost.toString());
			
		}
		logger.info("===========post request end======================");
		*/
		/*logger.info("===========put request start======================");
		String putUrl="http://localhost:8080/sendPutRequest";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", "李四");
		paramMap.put("sname", "张三");
		String doPost = doPut(paramMap,putUrl,"000000");
		System.out.println(doPost);
		logger.info("===========put request end======================");*/
		
		/*logger.info("===========delete request start======================");
		String deleteUrl="http://localhost:8080/sendDeleteRequest";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", "李四");
		String doDelete = doDelete(paramMap,deleteUrl,"000000");
		System.out.println(doDelete);
		logger.info("===========delete request end======================");*/
		
		logger.info("===========get request start======================");
		
		String deleteUrl="http://192.168.0.108:8089/weather-api/data-api/testbusinessbygetwangshunyi?name=张三";
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("name", "张三");
		String doGet = doGet(paramMap,deleteUrl,"000000");
		logger.info(doGet);
		logger.info("===========get request end======================");
	}
	public static BaseResponse forwardingRequest(String url,Map<String,Object> paramMap,String method,String contentType) {
		// 添加请求头信息
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		//headers.set("appKey", appKey);
		//headers.setContentType(mediaType);
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("appId", 60);
		HttpEntity<Object> request = new HttpEntity<Object>(paramMap, headers);
		RestTemplate restTemplate = new RestTemplate();
		System.out.println("Request Headers------: " + JSON.toJSON(headers));
		System.out.println("Request Body------: " + JSON.toJSON(request.getBody()));
		ResponseEntity<BaseResponse> responseEntity=null;
		if(method.equals("get")) {
			//responseEntity = restTemplate.exchange(url, HttpMethod.GET, request,BaseResponse.class);
			 responseEntity = restTemplate.getForEntity(url, BaseResponse.class,map);
			
		}else if(method.equals("post")){
			responseEntity = restTemplate.exchange(url, HttpMethod.POST, request,BaseResponse.class);
			
		}else if(method.equals("delete")){
			responseEntity = restTemplate.exchange(url, HttpMethod.DELETE, request,BaseResponse.class);
			
		}else{
			responseEntity = restTemplate.exchange(url, HttpMethod.PUT, request,BaseResponse.class);
		}
		
		return responseEntity.getBody();
		
	}
	
	private static String doOutSideGetApi(String url,Map<String,Object> paramMap,String contentType) {
	    // 添加请求头信息
		HttpHeaders headers = new HttpHeaders(); 
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		//headers.set("appKey", appKey);
		//headers.setContentType(mediaType);
		HttpEntity<Object> requestHeaders = new HttpEntity<Object>(null, headers);
		if(logger.isInfoEnabled()) {
			logger.info("this OutSideGetApi Request Headers:"+JSON.toJSONString(headers));
			logger.info("this OutSideGetApi Request Url:"+url);
			
		}
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> exchange = restTemplate.exchange(url,HttpMethod.GET,requestHeaders, String.class, paramMap);
		return exchange.getBody();
	}
	/**
	 * 
	 * @Description: 第三方地址的url 格式 http://localhost:8080/v1/apiManage/apiVersionDetails
	 * @param:map 拼接参数的占位符      
	 * @date:   2019年4月4日 下午3:24:31  
	 * @author: wangshunyi    
	 * @throws
	 */
	private static String getUrlParamsByMap(String url,Map<String, Object> map) {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        sb.append(url).append("?");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            sb.append(entry.getKey() + "={" + entry.getKey()+"}");
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = s.substring(0, s.length() - 1);
        }
        return s;
    }
}
